import 'package:flutter/material.dart';
import 'package:flutter_displaymode/flutter_displaymode.dart';

class OptimalMode extends StatefulWidget {
  Widget child;

  OptimalMode(this.child);

  @override
  _OptimalModeState createState() => _OptimalModeState(child);
}

class _OptimalModeState extends State<OptimalMode> {
  Widget child;

  _OptimalModeState(this.child);

  @override
  void initState() {
    setOptimalDisplayMode();
    super.initState();
  }

  @override
  Widget build(context) {
    return child;
  }

  Future<void> setOptimalDisplayMode() async {
    final List<DisplayMode> supported = await FlutterDisplayMode.supported;
    final DisplayMode active = await FlutterDisplayMode.active;

    final List<DisplayMode> sameResolution = supported
        .where((DisplayMode m) =>
            m.width == active.width && m.height == active.height)
        .toList()
      ..sort((DisplayMode a, DisplayMode b) =>
          b.refreshRate.compareTo(a.refreshRate));

    final DisplayMode mostOptimalMode =
        sameResolution.isNotEmpty ? sameResolution.first : active;

    /// This setting is per session.
    /// Please ensure this was placed with `initState` of your root widget.
    await FlutterDisplayMode.setPreferredMode(mostOptimalMode);
  }
}
